﻿//
//调用接口服务
//
(function ($) {
    $.fn.executeCommand = function (commandSetting, key, param) {
        var that = this;
        //判断是否正在执行命令
        if (that.attr('loading_command') == '1') {
            return;
        };
        if ($.mobile) {
            $.mobile.loading('show', {
                text: '加载中...',
                textVisible: true,
                theme: 'a',
                textonly: false
            });
        }
        var setting = {
            //服务地址
            serviceUrl: '/Interface/ajax/CommandService.aspx',
            //是否需要用户确认
            needConfirm: false,
            async:true,
            gotoUrl:'',
            confirmMsg: '确定执行此操作?',
            //执行成功回调
            successCallBack: function (result, totalCount) { },
            //执行错误回调
            errorCallback: function (errorCode, msg) { showTips(msg, 2000); }

        };
        $.extend(setting, commandSetting);

        if (!setting.needConfirm || (setting.needConfirm && confirm(setting.confirmMsg))) {
            that.attr('loading_command', '1');
            $.ajax({
                url: setting.serviceUrl + '?key=' + key,
                data: { key: key, param: $.toJSON(param), temp: new Date().valueOf() },
                type: 'POST',
                async:setting.async,
                dataType: 'json',
                cache: false,
                error: function (data) {
                    if ($.mobile) {
                        $.mobile.loading("hide");
                    }
                    that.attr('loading_command', '0');
                    //setting.errorCallback('9999', 'ajax获取数据发生错误，错误代码:' + data.status);
                },
                success: function (result) {
                    if ($.mobile) {
                        $.mobile.loading("hide");
                    }
                    that.attr('loading_command', '0');
                    if (result.IsError || result.Error) {
                        if (result.ErrorCode == "0109") {
                        	if(setting.gotoUrl == ''){
                          	location.href = "/wap/member/LoginWeixin.aspx?goto=" + encodeURIComponent(GetUrlRelativePath());
                          }
                          else{
                          	location.href = "/wap/member/LoginWeixin.aspx?goto=" + encodeURIComponent(setting.gotoUrl);
                          }
                        } else {
                            setting.errorCallback(result.ErrorCode, result.ErrorMsg);
                        }
                    } else {
                        setting.successCallBack(result.Result, result.TotalCount);
                    }
                }
            });
        }

    }

})(jQuery);

//
//format
//var template1 = "我是{0}，今年{1}了";
//var template2 = "我是{name}，今年{age}了";
//var result1=template1.format("loogn",22);
//var result2 = template2.format({ name: "loogn", age: 22 });
//两个结果都是"我是loogn，今年22了"
//
String.prototype.format = function (args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                if (args[key] != undefined) {
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                } else {
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, "");
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    var reg = new RegExp("({[" + i + "]})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
}

Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

//
// 带表单验证
//
function executeFormCommonCommand(formid, callback, onError) {
    $form = $("#" + formid);
    $form.trigger("validate");
    if ($form.isValid()) {
        executeCommonCommand($form, callback, onError);
    }
    else {
        return false;
    }
}

function firstThumbnail(json, thumbName) {
    var _thumbName = (thumbName ? thumbName : 'thumb');
    try {
        var imgArr = $.parseJSON(json);
        return ($.cookie('imagesvr') ? $.cookie('imagesvr') : '') + imgArr[0].FilePath + '.' + _thumbName + '.' + imgArr[0].FileExt;
    } catch (e) {
        return '';
    }
}

//获取第一个文件
function firstFilePath(json) {
    try {
        var fileArr = $.parseJSON(json);
        return ($.cookie('imagesvr') ? $.cookie('imagesvr') : '') + fileArr[0].FilePath;
    } catch (e) {
        return '';
    }
}

//获取网站路径，不带#之后的数据
function GetUrlPath() {
    var url = document.location.toString();
    var startSh = url.indexOf("#");
    if (startSh > 0) {
        return url.substring(0, startSh); //stop省略，截取从start开始到结尾的所有字符
    }
    else {
        return url;
    }
}

//获取网站相对路径，并且不带#之后的数据
function GetUrlRelativePath() {
    var url = document.location.toString();
    var arrUrl = url.split("//");
    var start = arrUrl[1].indexOf("/");
    var relUrl = arrUrl[1].substring(start); //stop省略，截取从start开始到结尾的所有字符
    var startSh = relUrl.indexOf("#");
    if (startSh > 0) {
        return relUrl.substring(0, startSh); //stop省略，截取从start开始到结尾的所有字符
    }
    else {
        return relUrl;
    }
}


//获取日期 yyyy-mm-dd
function getShortDateString(dateTimeString) {
//根据实际需要修改
    var mydate = new Date(dateTimeString.replace(/\-/g, "\/"));
    var dateYear = mydate.getFullYear();
    var dateMon = mydate.getMonth() + 1;
    var dateDay = mydate.getDate();

    var tempDate = dateYear + "-" + (dateMon < 10 ? "0" + dateMon : dateMon) + "-" + (dateDay < 10 ? "0" + dateDay : dateDay);
    return tempDate;
}
//获取时间
function getShortTimeString(dateTimeString) {
    //根据实际需要修改
    var mydate = new Date(dateTimeString.replace(/\-/g, "\/"));
    var dateHours = mydate.getHours();
    var dateMin = mydate.getMinutes();
    var dateSec = mydate.getSeconds();

    var tempTime = (dateHours < 10 ? "0" + dateHours : dateHours) + ":" + (dateMin < 10 ? "0" + dateMin : dateMin) + ":" + (dateSec < 10 ? "0" + dateSec : dateSec);

    return tempDate;
}
//转换时间格式yyyy-mm-dd hh:mm:ss
function convertDateTimeString(dateTimeString) {
    //根据实际需要修改
    var mydate = new Date(dateTimeString.replace(/\-/g, "\/"));
    var dateYear = mydate.getFullYear();
    var dateMon = mydate.getMonth() + 1;
    var dateDay = mydate.getDate() + 1;
    var dateHours = mydate.getHours();
    var dateMin = mydate.getMinutes();
    var dateSec = mydate.getSeconds();

    var tempDate = dateYear + "-" + (dateMon < 10 ? "0" + dateMon : dateMon) + "-" + (dateDay < 10 ? "0" + dateDay : dateDay);
    var tempTime = (dateHours < 10 ? "0" + dateHours : dateHours) + ":" + (dateMin < 10 ? "0" + dateMin : dateMin) + ":" + (dateSec < 10 ? "0" + dateSec : dateSec);

    return tempDate + " " + tempTime;
}

//转换时间格式 mm-dd hh:mm
function convertShortDateTimeString(dateTimeString) {
    //根据实际需要修改
    var mydate = new Date(dateTimeString.replace(/\-/g, "\/"));
    var dateYear = mydate.getFullYear();
    var dateMon = mydate.getMonth() + 1;
    var dateDay = mydate.getDate();
    var dateHours = mydate.getHours();
    var dateMin = mydate.getMinutes();
    var dateSec = mydate.getSeconds();

    var tempDate = (dateMon < 10 ? "0" + dateMon : dateMon) + "-" + (dateDay < 10 ? "0" + dateDay : dateDay);
    var tempTime = (dateHours < 10 ? "0" + dateHours : dateHours) + ":" + (dateMin < 10 ? "0" + dateMin : dateMin);

    return tempDate + " " + tempTime;
}

function executeCommonCommand(ui, callback, onError) {
    var param = {};
    ui.find('[command-param]').each(function () {
        if ($(this).attr('data-role') == 'controlgroup') {
            var val = '';
            $(this).find('input').each(function () {
                if (this.type == "radio") {
                    if ($(this)[0].checked == true) {
                        val = $(this).val();
                    }
                } else if (this.type == "checkbox") {
                    if ($(this)[0].checked == true) {
                        val += $(this).val() + ",";
                    }
                }
            });
            param[$(this).attr('command-param')] = val;
        } else {
            param[$(this).attr('command-param')] = $(this).val();
        }
    });
    ui.executeCommand({
        successCallBack: function (result) {
            if (typeof (callback) == "function") {
                callback(result);
            } else if (typeof (callback) == "string") {
                eval(callback + "(result)");
            }
            else {
                showTips('操作成功');
            }
        },
        errorCallback: function (errorCode, msg) {
            if (onError) {
                onError(errorCode, msg);
            } else {
                showTips(msg, 2000);
            }
        }
    }, ui.attr('command'), param);
}